# _*_ coding:utf-8 _*_
# @author : Joyamon
# @time : 2022-12-21 14:11
# @file : role.py
# https://www.freesion.com/article/1313167488/
from functools import wraps
from apps.user.models import Role, User
from flask import abort,session
from exts import session as se


def permission_can(current_user, permission):
    """
    检测用户是否有特定权限
    :param current_user
    :param permission
    :return:
    """
    role_id = current_user.role_id
    print('@',role_id)
    role = se.query(Role).filter_by(id=role_id).first()
    return (role.permissions & permission) == permission


def permission_required(permission):
    """
    权限认证装饰器
    :param permission:
    :return:
    """
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            try:
                current_user = User.query.filter_by(id=session.get('user_id')).first()
                if not current_user and permission_can(current_user, permission):
                    abort(403)
                return f(*args, **kwargs)
            except:
                abort(403)
        return decorated_function
    return decorator



